package com.imvc.service;

import com.imvc.exception.DbSessionException;
import com.imvc.util.DbSession;
import com.imvc.util.DbSessionFactory;

import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 业务代理对象
 *
 * @author ml
 * @create 2017-10-18--16:33
 */
public class ServiceProxy implements InvocationHandler {
    private Object target;
    public ServiceProxy(Object o){
        this.target = o;
    }

    public static Object getProxyInstance(Object target){
        Class<?> clazz=target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),new ServiceProxy(target));
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object retValue=null;
        DbSession session= DbSessionFactory.openSession();
        boolean TxFlag=!method.getName().startsWith("get");
        try {
            if(TxFlag) {
                session.beginTx();
            }

            retValue=method.invoke(target,args);

            if(TxFlag){
                session.commitTx();
            }
        }catch (DbSessionException ex){
            ex.printStackTrace();
            if(TxFlag){
                session.rollbackTx();
            }
        }
        return retValue;
    }
}
